package com.planw.beetl.utils;

import com.intellij.openapi.module.JavaModuleType;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleUtil;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiFile;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.idea.maven.model.MavenArtifact;
import org.jetbrains.idea.maven.project.MavenProject;
import org.jetbrains.idea.maven.project.MavenProjectsManager;

public class MavenUtil {

  public void getResourcePath(Project project, PsiFile containingFile) {

    Module module = ModuleUtil.findModuleForFile(containingFile.getOriginalFile());
    MavenProject mavenProject = MavenProjectsManager.getInstance(project).findProject(module);
  }

  public static int getBeetlSqlVersion(Project project) {

    Set<String> versionSet = new HashSet<>();
    MavenProjectsManager mavenProjectsManager = MavenProjectsManager.getInstance(project);
    Collection<Module> modules = ModuleUtil.getModulesOfType(project, new JavaModuleType());
    for (Module module : modules) {
      if (mavenProjectsManager.isMavenizedProject()) {
        MavenProject mavenProject = mavenProjectsManager.findProject(module);
        if (mavenProject == null) {
          continue;
        }
        List<MavenArtifact> mavenArtifacts = mavenProject.findDependencies("com.ibeetl",
            "beetlsql");
        if (mavenArtifacts.isEmpty()) {
          continue;
        }
        for (MavenArtifact mavenArtifact : mavenArtifacts) {
          String version = mavenArtifact.getVersion();
          if (version.startsWith("3")) {
            versionSet.add("3");
          }
          if (version.startsWith("2")) {
            versionSet.add("2");
          }
        }
      }
    }
    return (versionSet.isEmpty() || versionSet.contains("3")) ? 3 : 2;
  }

  public static boolean isDependOnBeetlSql(@Nullable Module module) {

    if (module == null) {
      return false;
    }

    Project project = module.getProject();
    MavenProjectsManager mavenProjectsManager = MavenProjectsManager.getInstance(project);
    MavenProject mavenProject = mavenProjectsManager.findProject(module);
    List<MavenArtifact> mavenArtifacts = mavenProject != null
        ? mavenProject.findDependencies("com.ibeetl", "beetlsql")
        : Collections.emptyList();
    return !mavenArtifacts.isEmpty();
  }

}
